package com.young.socket.websocket;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.inject.Singleton;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Singleton
@Component("webSocketService")
public class WebSocketService {

    /**
     * 交换键值对可改变推送策略
     */
    private static final ConcurrentMap<String, Long> userSessionMapping = new ConcurrentHashMap<>();

    private SocketMessageHandle socketMessageHandle;

    public WebSocketService() {
        log.info("===============初始化了WebSocketService===============");
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                for (Map.Entry<String, Long> userSession : userSessionMapping.entrySet()) {
                    socketMessageHandle.handle(userSession.getKey(), "Hello world!");
                }
            }
        }, 100, 10000);
    }

    public void pushUserMsg(Long userId, String msg) {
        if (null == socketMessageHandle) {
            log.error("推送用户[{}]消息异常，消息处理器不存在！", userId);
            return;
        }
        userSessionMapping.forEach((sid, uid) -> {
            if (uid.equals(userId)) {
                if (null == sid) {
                    log.error("推送用户[{}]消息异常，用户客户端不存在！", userId);
                    log.info("当前在线客户端[{}]", JSONObject.toJSONString(userSessionMapping));
                } else {
                    socketMessageHandle.handle(sid, msg);
                }
            }
        });
    }

    public void handleMessage(String sessionId, String message) {
        // TODO
    }

    public synchronized void registerUserSessionId(Long userId, String sessionId) {
        userSessionMapping.put(sessionId, userId);
    }

    public synchronized void removeUserSessionId(String sessionId) {
        userSessionMapping.remove(sessionId);
    }

    public void setSocketMessageHandle(SocketMessageHandle socketMessageHandle) {
        this.socketMessageHandle = socketMessageHandle;
    }

    public SocketMessageHandle getSocketMessageHandle() {
        return socketMessageHandle;
    }
}
